<?php

/**
 *
 */
class WebUser extends CWebUser {

    /**
     * get user model from session
     * @return User
     */
    public function getModel() {

	$model = Yii::app()->getSession()->get('current_user');
	if (!$model && !user()->isGuest) {
	    $model = User::model()->findByPk(user()->id);

	    //get ideal profile
	    $idealProfile = IdealProfile::getIdealProfile(user()->id);

	    if ($idealProfile) {
		if (isset($idealProfile['ideal_profile_id'])) {
		    unset($idealProfile['ideal_profile_id']);
		}
		if (isset($idealProfile['user_id'])) {
		    unset($idealProfile['user_id']);
		}
		$model->ideal_profile = $idealProfile;
	    }
	    Yii::app()->getSession()->add('current_user', $model);
	}

	return $model;
    }

    public function setModel($model) {
	Yii::app()->getSession()->add('current_user', $model);
    }

    public function login($identity, $duration = 0) {
	parent::login($identity, $duration);
//	Yii::app()->getSession()->add('current_user', $identity->getModel());
	$identity->getModel();
	return $this;
    }

    /**
     * destroy some session variables
     * @param type $destroySession
     */
    public function logout($destroySession = true) {
	// I always remove the session variable model.
	Yii::app()->getSession()->remove('current_user');

	parent::logout($destroySession);
    }

    public function getUsername() {
	return $this->getUserProperty('display_name');
    }

    public function getUserProperty($keyname) {
	if (!$this->isLogged())
	    return "";
	$user = Yii::app()->getSession()->get('current_user');
	//var_dump($user->attributes);
	return $user->{$keyname};
    }

    public function isLogged() {
	return !(Yii::app()->user->isGuest);
    }

}

